﻿package com.cloud.servlet;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cloud.core.BaseServlet;
import com.cloud.core.emchat.ChatAdmin;
import com.cloud.core.redis.RedisClient;
import com.cloud.core.sms.SmsService;
import com.cloud.dao.ContactBean;
import com.cloud.dao.CrcBean;
import com.cloud.dao.DoctorBean;
import com.cloud.dao.DoctorInfo;
import com.cloud.dao.MyPatientBean;
import com.cloud.dao.UserBean;
import com.cloud.service.CrcService;
import com.cloud.service.DoctorService;
import com.cloud.service.FileService;
import com.cloud.service.MyPatientService;
import com.cloud.service.UserService;
import com.cloud.util.Code;
import com.cloud.util.CommUtil;
import com.cloud.util.Notice;
import com.google.gson.JsonObject;

/**
 * 1Cloud1
 * @author Administrator
 * @since 2015-11-4
 * @version 1.0 
 */
@Controller
@RequestMapping("/user")
public class UserServlet extends BaseServlet {
	private static final Logger logger = LoggerFactory.getLogger(UserServlet.class);
	private final String code_prefix = CommUtil.code_prefix;
	private final String code_time_prefix = CommUtil.code_time_prefix;
	@Autowired
	private UserService UserService;
	@Autowired
	private FileService FileService;
	@Autowired
	private ChatAdmin ChatAdmin;
	@Autowired
	private DoctorService DoctorService;
	@Autowired
	private MyPatientService MyPatientService;
	@Autowired
	private SmsService SmsService;
	@Autowired
	private RedisClient RedisClient;
	@Autowired
	private CrcService CrcService;
	
	/**
	 * 用户登陆
	 * @param request
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/login", method = { RequestMethod.POST})
	public @ResponseBody Object login(HttpServletRequest request, @RequestBody UserBean user) {
		Map<String, Object> map = new HashMap<String, Object>();
		if(user == null || CommUtil.isEmpty(user.getUserName()) || CommUtil.isEmpty(user.getPassWord()) ){ //|| CommUtil.isEmpty(user.getClientType())
			map.put("code", Code.C400.key);
			map.put("msg", Code.C400.desc);
			return map;
		}
		List<UserBean> retUserList = new ArrayList<UserBean>();
		UserBean _user = new UserBean();
		_user.setUserName(user.getUserName());
		_user.setClientType(user.getClientType());
		_user.setMd5Pwd(CommUtil.MD5(user.getPassWord()));
		retUserList = UserService.getUserList(_user);
		if(retUserList.size() == 0){
			map.put("code", Code.C430.key);
			map.put("msg", Code.C430.desc);
			return map;
		}
		map.put("code", Code.C200.key);
		map.put("msg", Code.C200.desc);
		map.put("data", retUserList.get(0).getUserId());
		map.put("clientType", retUserList.get(0).getClientType());
		return map;
	}

	/**
	 * 查询用户
	 * @param request
	 * @param userid
	 * @return
	 */
	@RequestMapping(value = "/{userid}/info", method = { RequestMethod.GET})
	public @ResponseBody Object list(HttpServletRequest request, @PathVariable String userid) {
		Map<String, Object> map = new HashMap<String, Object>();
		if(CommUtil.isEmpty(userid)){
			map.put("code", Code.C400.key);
			map.put("msg", Code.C400.desc);
			return map;
		}
		UserBean user = new UserBean();
		user.setUserId(userid);
		List<UserBean> retUserList = UserService.getUserList(user);
		Map<String, String> _map = new HashMap<String, String>();
		if(retUserList != null && retUserList.size() == 1){
			UserBean bean = retUserList.get(0);
			_map.put("userId", bean.getUserId());
			_map.put("userName", bean.getUserName());
			_map.put("fullName", bean.getFullname());
			_map.put("nikeName", bean.getNikeName());
			_map.put("clientType", bean.getClientType());
			_map.put("head", FileService.getVisitUrl(bean.getCrcurl()));
			_map.put("email", bean.getEmail());
			_map.put("mobile", bean.getMobile());
			_map.put("createTime", bean.getCreateTime());
		}
		map.put("code", Code.C200.key);
		map.put("msg", Code.C200.desc);
		map.put("data", _map);
		return map;
	}
	
	/**
	 * 查询联系人
	 * @param request
	 * @param contacts
	 * @return
	 */
	@RequestMapping(value = "/contacts", method = { RequestMethod.GET})
	public @ResponseBody Object contacts(HttpServletRequest request, ContactBean contacts) {
		Map<String, Object> map = new HashMap<String, Object>();
		if(contacts == null || contacts.getUserId() == null || contacts.getUserId().trim().length() == 0){
			map.put("code", Code.C400.key);
			map.put("msg", Code.C400.desc);
			return map;
		}
		DoctorBean doctor = new DoctorBean();
		doctor.setId(contacts.getUserId());
		List<DoctorInfo> retDoctorList = new ArrayList<DoctorInfo>();
		retDoctorList = DoctorService.queryDoctorContact(doctor);
		for(DoctorInfo info : retDoctorList){
			if(!CommUtil.isEmpty(info.getCrcHead()))
				info.setCrcHead(FileService.getVisitUrl(info.getCrcHead()));
			if(!CommUtil.isEmpty(info.getLicense()))
				info.setLicense(FileService.getVisitUrl(info.getLicense()));
		}
		map.put("code", Code.C200.key);
		map.put("msg", Code.C200.desc);
		map.put("data", retDoctorList);
		return map;
	}
	
	/**
	 * 查询联系人CRC
	 * @param request
	 * @param contacts
	 * @return
	 */
	@RequestMapping(value = "/crc", method = { RequestMethod.GET})
	public @ResponseBody Object crc(HttpServletRequest request, ContactBean contacts) {
		Map<String, Object> map = new HashMap<String, Object>();
		if(contacts == null || contacts.getUserId() == null || contacts.getUserId().trim().length() == 0){
			map.put("code", Code.C400.key);
			map.put("msg", Code.C400.desc);
			return map;
		}
		CrcBean crc = new CrcBean();
		crc.setId(contacts.getUserId());
		List<CrcBean> retCrcList = new ArrayList<CrcBean>();
		retCrcList = CrcService.queryCrcContact(crc);
		for(CrcBean bean : retCrcList){
			if(!CommUtil.isEmpty(bean.getCrc()))
				bean.setCrc(FileService.getVisitUrl(bean.getCrc()));
		}
		List<Map<String, String>> data = new ArrayList<Map<String, String>>();
		for(CrcBean bean : retCrcList){
			Map<String, String> _map = new HashMap<String, String>();
			_map.put("id", bean.getId());
			_map.put("dic_id", bean.getDic_id());
			_map.put("crcHead", bean.getCrc());
			_map.put("userName", bean.getUserName());
			_map.put("name", bean.getFullname());
			_map.put("gender", bean.getGender());
			_map.put("birthday", bean.getBirthday());
			_map.put("idcard", bean.getIdcard());
			_map.put("comName", bean.getCom_id());
			_map.put("desc", bean.getIntroduction());
			_map.put("createTime", bean.getCreateTime());
			data.add(_map);
		}
		map.put("code", Code.C200.key);
		map.put("msg", Code.C200.desc);
		map.put("data", data);
		return map;
	}
	
	@RequestMapping(value = "/contacts--before/_old", method = { RequestMethod.GET})
	public @ResponseBody Object _contacts(HttpServletRequest request, ContactBean contacts) {
		Map<String, Object> map = new HashMap<String, Object>();
		if(contacts == null || contacts.getUserId() == null || contacts.getUserId().trim().length() == 0){
			map.put("code", Code.C400.key);
			map.put("msg", Code.C400.desc);
			return map;
		}
		List<ContactBean> retUserContactList = new ArrayList<ContactBean>();
		contacts.setStatus("0");
		retUserContactList = UserService.getUserContactList(contacts, false);
		List<Map<String, String>> data = new ArrayList<Map<String, String>>();
		for(ContactBean bean : retUserContactList){
			Map<String, String> _map = new HashMap<String, String>();
			_map.put("userId", bean.getUserId());
			_map.put("userName", bean.getUserName());
			_map.put("head", FileService.getVisitUrl(bean.getHead()));
			_map.put("createTime", bean.getCreateTime());
			data.add(_map);
		}
		map.put("code", Code.C200.key);
		map.put("msg", Code.C200.desc);
		map.put("data", data);
		return map;
	}
	
	/**
	 * 邀请联系人
	 * @param request
	 * @param from
	 * @param contacts
	 * @return
	 */
	@RequestMapping(value = "/{from}/invite", method = { RequestMethod.POST})
	public @ResponseBody Object inviteContacts(HttpServletRequest request, @PathVariable String from, String contacts) {
		Map<String, Object> map = new HashMap<String, Object>();
		if(contacts == null || contacts.trim().length() == 0){
			map.put("code", Code.C400.key);
			map.put("msg", Code.C400.desc);
			return map;
		}
		ContactBean cbean = new ContactBean();
		cbean.setUserId(from);
		List<ContactBean> retUserContactList = UserService.getUserContactList(cbean, false);
		List<UserBean> retUserList = UserService.getUserList(new UserBean());
		Set<String> _contactsSet = new HashSet<String>(Arrays.asList(contacts.split(",")));
		List<ContactBean> listContactBean = new ArrayList<ContactBean>();
		for(String uid : _contactsSet){
			boolean isExit = false;
			boolean isCont = false;
			for(UserBean bean : retUserList){
				if(uid.equalsIgnoreCase(bean.getUserId())){
					isExit = true;
					break;
				}
			}
			for(ContactBean bean : retUserContactList){
				if(uid.equalsIgnoreCase(bean.getContactId())){
					isCont = true;
					break;
				}
			}
			if(isExit && !isCont){
				ContactBean _bean = new ContactBean();
				_bean.setUserId(from);
				_bean.setContactId(uid);
				listContactBean.add(_bean);
			}
		}
		if(listContactBean .size() < 1){
			map.put("code", Code.C420.key);
			map.put("msg", Code.C420.desc);
			return map;
		}
		UserService.addUserContact(listContactBean);
		StringBuffer toInvite = new StringBuffer();
		for(UserBean _ubean : retUserList){
			for(ContactBean _cbean : listContactBean){
				if(_cbean.getContactId().equalsIgnoreCase(_ubean.getUserId())){
					toInvite.append(",").append(_ubean.getUserName());
					break;
				}
			}
		}
		ChatAdmin.sendMessage(from, toInvite.toString().substring(1), Notice.InviteFriend);
		map.put("code", Code.C200.key);
		map.put("msg", Code.C200.desc);
		return map;
	}
	
	/**
	 * 邀请联系人通知
	 * @param request
	 * @param from
	 * @return
	 */
	@RequestMapping(value = "/{from}/invite/notice", method = { RequestMethod.GET})
	public @ResponseBody Object inviteContactsNotice(HttpServletRequest request, @PathVariable String from) {
		Map<String, Object> map = new HashMap<String, Object>();
		ContactBean cbean = new ContactBean();
		cbean.setUserId(from);
		cbean.setStatus("1");
		List<ContactBean> retUserContactList = UserService.getUserContactList(cbean, true);
		List<Map<String, String>> data = new ArrayList<Map<String, String>>();
		for(ContactBean bean : retUserContactList){
			Map<String, String> _map = new HashMap<String, String>();
			_map.put("userId", bean.getUserId());
			_map.put("userName", bean.getUserName());
			_map.put("head", FileService.getVisitUrl(bean.getHead()));
			_map.put("createTime", bean.getCreateTime());
			data.add(_map);
		}
		map.put("code", Code.C200.key);
		map.put("msg", Code.C200.desc);
		map.put("data", data);
		return map;
	}
	
	/**
	 * 联系人(医生)应答
	 * @param request
	 * @param owner
	 * @param code
	 * @return
	 */
	@RequestMapping(value = "/{from}/{to}/invite/res", method = { RequestMethod.POST})
	public @ResponseBody Object inviteContactsRespose(HttpServletRequest request, @PathVariable String from, @PathVariable String to, String code) {
		Map<String, Object> map = new HashMap<String, Object>();
		if(code == null || code.trim().length() == 0){
			map.put("code", Code.C400.key);
			map.put("msg", Code.C400.desc);
			return map;
		}
		ContactBean cbean = new ContactBean();
		cbean.setUserId(to);
		cbean.setContactId(from);
		UserBean user = new UserBean();
		user.setUserId(to);
		List<UserBean> retUserList = UserService.getUserList(user);
		logger.info(from+"============="+to+"======"+code);
		if("0".equalsIgnoreCase(code)){ //拒绝
			cbean.setStatus("2");
			UserService.updateUserContact(cbean);
			if(retUserList != null && retUserList.size() != 0)
				ChatAdmin.sendMessage(from, retUserList.get(0).getUserName(), Notice.InviteFriendNo);
		}
		if("1".equalsIgnoreCase(code)){ //同意
			cbean.setStatus("0");
			UserService.updateUserContact(cbean);
			MyPatientBean mypatient = new MyPatientBean();
			mypatient.setDoc_id(from);
			mypatient.setPat_id(to);
			mypatient.setStatus("0");
			mypatient.setPro_id("-1");
			MyPatientService.addMyPatient(mypatient);
			if(retUserList != null && retUserList.size() != 0)
				ChatAdmin.sendMessage(from, retUserList.get(0).getUserName(), Notice.InviteFriendOk);
		}
		map.put("code", Code.C200.key);
		map.put("msg", Code.C200.desc);
		return map;
	}
	
	/**
	 * 修改账户信息
	 * @param request
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/information/update", method = { RequestMethod.POST})
	public @ResponseBody Object license(HttpServletRequest request, @RequestBody UserBean user) {
		Map<String, Object> map = new HashMap<String, Object>();
		if(user == null || CommUtil.isEmpty(user.getUserId()) || (!CommUtil.isEmpty(user.getPassWord()) && CommUtil.isEmpty(user.getUserName()))){
			map.put("code", Code.C400.key);
			map.put("msg", Code.C400.desc);
			return map;
		}
		if(!CommUtil.isEmpty(user.getPassWord())){
			try {
				JsonObject json = ChatAdmin.changePwd(user.getUserName(), user.getPassWord());
				if(!json.toString().toLowerCase().contains("set user password")){
					map.put("code", Code.C412.key);
					map.put("msg", Code.C412.desc);
					return map;
				}
			} catch (Exception e) {
				map.put("code", Code.C412.key);
				map.put("msg", Code.C412.desc);
				return map;
			}
			user.setMd5Pwd(CommUtil.MD5(user.getPassWord()));
		}
		try {
			UserService.updateUser(user, true);
		} catch (Exception e) {
			map.put("code", Code.C400.key);
			map.put("msg", Code.C400.desc);
			return map;
		}
		map.put("code", Code.C200.key);
		map.put("msg", Code.C200.desc);
		return map;
	}
	
	@RequestMapping(value = "/reset/pwd", method = { RequestMethod.POST})
	public @ResponseBody Object register(HttpServletRequest request, @RequestBody UserBean user) {
		Map<String, Object> map = new HashMap<String, Object>();
		if(user == null || CommUtil.isEmpty(user.getUserName()) || CommUtil.isEmpty(user.getPassWord())){
			map.put("code", Code.C400.key);
			map.put("msg", Code.C400.desc);
			return map;
		}
		UserBean _user = new UserBean();
		_user.setUserName(user.getUserName());
		_user.setPassWord(user.getPassWord());
		//是否发送验证码校验
		boolean isSend = Boolean.valueOf(CommUtil.isEmpty(SmsService.getSmssend()) ? "true" : SmsService.getSmssend());
		String key = code_prefix.concat(_user.getUserName());
		String keynum = code_time_prefix.concat(_user.getUserName());
		if(isSend){
			String code = RedisClient.get(key);
			boolean isValid = !CommUtil.isEmpty(code) && "ok".equals(code.split("_")[1]);
			if(!isValid){
				map.put("code", Code.C413.key);
				map.put("msg", Code.C413.desc);
				return map;
			}
		}
		try {
			JsonObject json = ChatAdmin.changePwd(_user.getUserName(), _user.getPassWord());
			if(!json.toString().toLowerCase().contains("set user password")){
				map.put("code", Code.C412.key);
				map.put("msg", Code.C412.desc);
				return map;
			}
		} catch (Exception e) {
			map.put("code", Code.C412.key);
			map.put("msg", Code.C412.desc);
			return map;
		}
		_user.setMd5Pwd(CommUtil.MD5(_user.getPassWord()));
		try {
			UserService.updateUser(_user, false);
		} catch (Exception e) {
			map.put("code", Code.C400.key);
			map.put("msg", Code.C400.desc);
			return map;
		}
		if(isSend){
			RedisClient.del(keynum);
			RedisClient.del(key);
		}
		map.put("code", Code.C200.key);
		map.put("msg", Code.C200.desc);
		return map;
	}
}
